import { Http, Headers, Response,Jsonp, RequestOptions, URLSearchParams } from '@angular/http';
import 'rxjs/add/operator/toPromise';

import { Injectable } from '@angular/core';

import { Role } from './role';
import { SERVER } from '../../app.config';

@Injectable()
export class RoleService {

    constructor(private http: Http){

    }

    getRoles(): Promise<Role[]> {
        return this.http.get(SERVER.ROLE)
        .toPromise()
        .then(response => response.json() as Role[])
        .catch(this.handleError);
    }

    getRole(role_id: number) {
        return this.getRoles()
            .then(roles => roles.find(role => role.role_id ===role_id ));
    }

    private handleError(error: any): Promise<any> {
        console.error('错误：', error);

        return Promise.reject(error.message || error);
    }

    //添加
    private post(role: Role): Promise<Role> {
        let headers = new Headers({
            'Content-type': 'application/json'});

        return this.http.post(SERVER.ROLE, JSON.stringify(role), {headers: headers})
        .toPromise()
        // .then(res => res.json())
        .catch(this.handleError);
    }

    //更新
    private put(role: Role): Promise<Role> {
        let headers = new Headers();
        headers.append('Content-Type', 'application/json');

        let url = `${SERVER.ROLE}` + '/'+ role.role_id;

        return this.http.put(url, JSON.stringify(role), {headers: headers})
                   .toPromise()
                   .then(() => role)
                   .catch(this.handleError);
    }

    //删除
    delete(role: Role): Promise<Response> {
        let headers = new Headers();
        headers.append('Content-Type', 'application/json');

        let url = `${SERVER.ROLE}/${role.role_id}`;

        return this.http
                   .delete(url, { headers: headers})
                   .toPromise()
                   .catch(this.handleError);
    }

    //保存
    save(role: Role): Promise<Role> {
        if (role.role_id) {
            return this.put(role)
        }
        return this.post(role);
    }
}